package com.guet.niit.Login.controller.admin;

import com.guet.niit.Admin.dao.AgentDaolmpl;
import com.guet.niit.Admin.dao.ChargingDaolmpl;
import com.guet.niit.Admin.dao.ChargingPileDaolmpl;
import com.guet.niit.Admin.dao.UserDaolmpl;
import com.guet.niit.Admin.pojo.Agent;
import com.guet.niit.Admin.pojo.Charging;
import com.guet.niit.Admin.pojo.ChargingPile;
import com.guet.niit.Admin.pojo.User;
import com.guet.niit.Login.pojo.StationData;
import com.guet.niit.util.adminSwitchoverMenu;
import com.guet.niit.util.exitLogin;
import com.sun.javafx.stage.StageHelper;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

public class ChargingStationManageFxController implements Initializable {
    public static ChargingStationManageFxController chargingStationManageFxController;

    @FXML
    private MenuItem stationPileManage;

    @FXML
    private MenuItem agentManage;

    @FXML
    private MenuItem userManage;

    @FXML
    private MenuItem mainMenu;

    @FXML
    private MenuItem exit;

    @FXML
    private ChoiceBox<?> condition;

    @FXML
    private TextField inputCondition;

    @FXML
    private TableView<StationData> tableView;
    private ObservableList<StationData> data = FXCollections.observableArrayList();

    @FXML
    private TableColumn<StationData, String> tc_stationName;

    @FXML
    private TableColumn<StationData, String> tc_city;

    @FXML
    private TableColumn<StationData, String> tc_address;

    @FXML
    private TableColumn<StationData, String> tc_agentName;

    @FXML
    private TableColumn<StationData, Double> tc_parkingFee;

    @FXML
    private TableColumn<StationData, Integer> tc_haveParkingFee;

    @FXML
    private TableColumn<StationData, Double> tc_rent;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        chargingStationManageFxController = this;
    }

    /**
     * 通过菜单子项进入充电桩管理
     * @param actionEvent
     */
    public void enterStationPileManageByMenuItem(ActionEvent actionEvent) {
        String text = stationPileManage.getText();
        adminSwitchoverMenu.backtrack(ChargingStationManageFxController.class,text);
        //调用dao层查询充电桩表
        ChargingPileDaolmpl chargingPileDao = new ChargingPileDaolmpl();
        List<ChargingPile> chargingPiles = chargingPileDao.chargingPileInquire();

        //读取充电桩列表信息
        ChargingPileManageFxController.chargingPileManageFxController.readStationPileInfo(chargingPiles);
    }

    /**
     * 通过菜单子项进入代理商管理
     * @param actionEvent
     */
    public void enterAgentManageByMenuItem(ActionEvent actionEvent) {
        String text = agentManage.getText();
        adminSwitchoverMenu.backtrack(ChargingStationManageFxController.class,text);
        //调用dao层查询代理商表
        AgentDaolmpl agentDao = new AgentDaolmpl();
        List<Agent> agents = agentDao.agentInquire();

        //读取代理商列表信息
        AgentManageFxController.agentManageFxController.readAgentInfo(agents);
    }

    /**
     * 通过菜单子项进入用户管理
     * @param actionEvent
     */
    public void enterUserManageByMenuItem(ActionEvent actionEvent) {
        String text = userManage.getText();
        adminSwitchoverMenu.backtrack(ChargingStationManageFxController.class,text);
        //调用dao层查询用户表
        UserDaolmpl userDao = new UserDaolmpl();
        List<User> users = userDao.userInquire();

        //读取用户列表信息
        UserManageFxController.userManageFxController.readUserInfo(users);
    }

    /**
     * 通过菜单子项进入主菜单
     * @param actionEvent
     */
    public void enterMainMenuByMenuItem(ActionEvent actionEvent) {
        String text = mainMenu.getText();
        adminSwitchoverMenu.backtrack(ChargingStationManageFxController.class,text);
    }

    /**
     * 点击菜单项的退出项退出系统
     * @param actionEvent
     */
    public void clickExit(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText(null);
        alert.setContentText("您确定要退出吗？");
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.OK){
//            Platform.exit();
            exitLogin.backtrack(ChargingStationManageFxController.class);
        }else {
            alert.close();
        }
    }

    /**
     * 读取充电站列表信息
     * @param stations
     */
    public void readStationsInfo(List<Charging> stations){
        setTableDataAfterSelectAll(stations);
    }

    /**
     * 条件查询
     * @param mouseEvent
     */
    public void conditionQuery(MouseEvent mouseEvent) {
        String keyWord = null;
        //获取用户输入的关键词
        keyWord = inputCondition.getText();
        if (keyWord.equals("")){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText(null);
            alert.setContentText("您还没有输入查询的关键词!");
            alert.showAndWait();
            return;
        }else {
            //获取用户选择的查询条件
            String queryCondition = condition.getValue().toString();
            //调用dao层查询充电站表
            ChargingDaolmpl chargingDao = new ChargingDaolmpl();
            if (queryCondition.equals("城市")){
                //查询条件为城市
                List<Charging> chargingByCity = chargingDao.chargingInquireByCity(keyWord);
                setTableDataAfterConditionQuery(chargingByCity);
            }else {
                //查询条件为有无停车费
                if (keyWord.equals("无")){
                    keyWord = "0";
                    int queryKeyWord = Integer.parseInt(keyWord);
                    List<Charging> chargingByParkingFee = chargingDao.chargingInquireByParkingFee(queryKeyWord);
                    setTableDataAfterConditionQuery(chargingByParkingFee);
                }else {
                    keyWord = "1";
                    int queryKeyWord = Integer.parseInt(keyWord);
                    List<Charging> chargingByParkingFee = chargingDao.chargingInquireByParkingFee(queryKeyWord);
                    setTableDataAfterConditionQuery(chargingByParkingFee);
                }
            }
        }
    }

    /**
     * 查询所有时设置充电站表格数据
     * @param stations
     */
    public void setTableDataAfterSelectAll(List<Charging> stations){
        //转存数据
        for (int i = 0; i < stations.size(); i++) {
            //转存充电站名
            String oriStationName = stations.get(i).getStation_name();
            StringProperty stationName = new SimpleStringProperty(oriStationName);
            //转存所属城市
            String oriCity = stations.get(i).getCity();
            StringProperty city = new SimpleStringProperty(oriCity);
            //转存地址
            String oriAddress = stations.get(i).getAddress();
            StringProperty address = new SimpleStringProperty(oriAddress);
            //转存代理商id
            Long oriAgentId = stations.get(i).getAgent_id();
            SimpleLongProperty longAgentId = new SimpleLongProperty(oriAgentId);
            StringProperty agentId = new SimpleStringProperty();
            agentId.set(String.valueOf(longAgentId.get()));
            //转存停车费
            Double oriParkingFee = stations.get(i).getParking_fee();
            SimpleDoubleProperty parkingFee = new SimpleDoubleProperty(oriParkingFee);
            //转存有无停车费
            Integer oriHaveParkingFee = stations.get(i).getHave_parking_fee();
            StringProperty haveParkingFee;
            //将0和1转化为"无"和"有"
            if (oriHaveParkingFee==0){
                //没有停车费
                String stringHaveParkingFee = "无";
                haveParkingFee = new SimpleStringProperty(stringHaveParkingFee);
            }else {
                //有停车费
                String stringHaveParkingFee = "有";
                haveParkingFee = new SimpleStringProperty(stringHaveParkingFee);
            }
            //转存租金
            Double oriRent = stations.get(i).getRent();
            SimpleDoubleProperty rent = new SimpleDoubleProperty(oriRent);
            //装入数据模型
            data.add(new StationData(stationName,city,address,agentId,parkingFee,haveParkingFee,rent));
        }

        //对代理商名进行单独处理
        //调用service层查询代理商名
        //查询代理商表信息通过在充电站表获取代理商id查询
        AgentDaolmpl agentDaolmpl = new AgentDaolmpl();
        List<Agent> agents = agentDaolmpl.selectAgentBeforeSelectStation();
        //获取并设置代理商名
        for (int i = 0; i < stations.size(); i++) {
            data.get(i).setAgentName(agents.get(i).getUsername());
        }

        //绑定数据
        tc_stationName.setCellValueFactory(cellData -> cellData.getValue().stationNameProperty());
        tc_city.setCellValueFactory(cellData -> cellData.getValue().cityProperty());
        tc_address.setCellValueFactory(cellData -> cellData.getValue().addressProperty());
        tc_agentName.setCellValueFactory(cellData -> cellData.getValue().agentNameProperty());
        tc_parkingFee.setCellValueFactory(new PropertyValueFactory<StationData,Double>("parkingFee"));
        tc_haveParkingFee.setCellValueFactory(new PropertyValueFactory<StationData,Integer>("haveParkingFee"));
        tc_rent.setCellValueFactory(new PropertyValueFactory<StationData,Double>("rent"));
        tableView.setItems(data);
    }

    /**
     * 条件查询时设置充电站表格数据
     * @param stations
     */
    public void setTableDataAfterConditionQuery(List<Charging> stations){
        //使用条件查询时，发现数据模型已有数据，需要先把数据模型清空再添加新数据
        emptyData();

        StringProperty agentId = null;
        //转存数据
        for (int i = 0; i < stations.size(); i++) {
            //转存充电站名
            String oriStationName = stations.get(i).getStation_name();
            StringProperty stationName = new SimpleStringProperty(oriStationName);
            //转存所属城市
            String oriCity = stations.get(i).getCity();
            StringProperty city = new SimpleStringProperty(oriCity);
            //转存地址
            String oriAddress = stations.get(i).getAddress();
            StringProperty address = new SimpleStringProperty(oriAddress);
            //转存代理商id
            Long oriAgentId = stations.get(i).getAgent_id();
            SimpleLongProperty longAgentId = new SimpleLongProperty(oriAgentId);
            agentId = new SimpleStringProperty();
            agentId.set(String.valueOf(longAgentId.get()));
            //转存停车费
            Double oriParkingFee = stations.get(i).getParking_fee();
            SimpleDoubleProperty parkingFee = new SimpleDoubleProperty(oriParkingFee);
            //转存有无停车费
            Integer oriHaveParkingFee = stations.get(i).getHave_parking_fee();
            StringProperty haveParkingFee;
            //将0和1转化为"无"和"有"
            if (oriHaveParkingFee==0){
                //没有停车费
                String stringHaveParkingFee = "无";
                haveParkingFee = new SimpleStringProperty(stringHaveParkingFee);
            }else {
                //有停车费
                String stringHaveParkingFee = "有";
                haveParkingFee = new SimpleStringProperty(stringHaveParkingFee);
            }
            //转存租金
            Double oriRent = stations.get(i).getRent();
            SimpleDoubleProperty rent = new SimpleDoubleProperty(oriRent);
            //装入数据模型
            data.add(new StationData(stationName,city,address,agentId,parkingFee,haveParkingFee,rent));
        }

        //对代理商名进行单独处理
        //调用service层查询代理商名
        //查询代理商表信息通过在充电站表获取代理商id查询
        AgentDaolmpl agentDaolmpl = new AgentDaolmpl();
        long queryAgentId = Long.parseLong(agentId.get());
        List<Agent> agents = agentDaolmpl.selectAgentBeforeSelectStation(queryAgentId);
        //获取并设置代理商名
        for (int i = 0; i < stations.size(); i++) {
            data.get(i).setAgentName(agents.get(i).getUsername());
        }

        //绑定数据
        tc_stationName.setCellValueFactory(cellData -> cellData.getValue().stationNameProperty());
        tc_city.setCellValueFactory(cellData -> cellData.getValue().cityProperty());
        tc_address.setCellValueFactory(cellData -> cellData.getValue().addressProperty());
        tc_agentName.setCellValueFactory(cellData -> cellData.getValue().agentNameProperty());
        tc_parkingFee.setCellValueFactory(new PropertyValueFactory<StationData,Double>("parkingFee"));
        tc_haveParkingFee.setCellValueFactory(new PropertyValueFactory<StationData,Integer>("haveParkingFee"));
        tc_rent.setCellValueFactory(new PropertyValueFactory<StationData,Double>("rent"));
        tableView.setItems(data);
    }

    /**
     * 清空表格中原有的数据
     */
    public void emptyData(){
        //清空原有数据
        for (int i = 0; i < data.size(); i++) {
            data.remove(i);
            i--;
        }
    }

    /**
     * 点击按钮新增数据
     * @param mouseEvent
     */
    public void AddRowData(MouseEvent mouseEvent) {
        //引用fxml样式
        Parent load = null;
        try {
            load = FXMLLoader.load(getClass().getResource("/fxml/admin/modifyChargingStationData.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObservableList<Stage> stageList = StageHelper.getStages();
        stageList.get(0).setScene(new Scene(load));
    }

    /**
     * 点击按钮修改数据
     * @param mouseEvent
     */
    public void updateRowData(MouseEvent mouseEvent) {
        //获取用户选中的行
        StationData selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem==null){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("修改失败!");
            alert.setContentText("原因：您还没有选择需要修改的行");
            alert.showAndWait();
        }else {
            //引用fxml样式
            Parent load = null;
            try {
                load = FXMLLoader.load(getClass().getResource("/fxml/admin/modifyChargingStationData.fxml"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            ObservableList<Stage> stageList = StageHelper.getStages();
            stageList.get(0).setScene(new Scene(load));
            //回显原数据
            ModifyStationDataFxController.modifyStationDataFxController.showData(selectedItem);
        }
    }

    /**
     * 点击按钮删除数据
     * @param mouseEvent
     */
    public void deleteRowData(MouseEvent mouseEvent) {
        //获取用户选中的行
        StationData selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem==null){
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setHeaderText("删除失败!");
            alert.setContentText("原因：您还没有选择需要删除的行");
            alert.showAndWait();
        }
        //调用service层查询充电站id
        ChargingDaolmpl chargingDao = new ChargingDaolmpl();
        Charging chargings = chargingDao.selectStationIdByStationName(selectedItem.getStationName());
        long deletedStationId = chargings.getId();
        //调用service层删除充电站数据
        boolean condition = chargingDao.chargingDelete(deletedStationId);
        if (condition){
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setHeaderText(null);
            alert.setContentText("删除成功!");
            alert.showAndWait();
            //更新数据
            //调用dao层查询充电站表
            List<Charging> stations = chargingDao.chargingInquire();

            //读取充电站列表信息
           setTableDataAfterDeletedData(stations);
        }
    }

    /**
     * 删除数据后设置充电站表格数据
     * @param stations
     */
    public void setTableDataAfterDeletedData(List<Charging> stations) {
        //清空原有数据
        emptyData();
        //更新数据
        setTableDataAfterSelectAll(stations);
    }

    /**
     * 关于我们
     * @param actionEvent
     */
    public void aboutUs(ActionEvent actionEvent) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText("关于我们");
        alert.setContentText("充电桩管理系统由Power-station项目组人员开发，本管理系统目前已实现四个模块的增删改查。");
        alert.showAndWait();
    }
}
